<template>
  <div class="video-container">
    <div class="wrap">
      <div style="margin-top: 20px" class="Breadcrumb">
        <el-breadcrumb separator="/">
          <el-breadcrumb-item :to="{ path: '/' }">全部课程</el-breadcrumb-item>
          <el-breadcrumb-item>课程详情</el-breadcrumb-item>
          <el-breadcrumb-item>课程视频</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
      <div class="video">
        <video
          ref="videoPlayer"
          v-if="playURL"
          :src="playURL"
          controls
          preload="auto"
          @timeupdate="saveWatchPosition"
          width="100%"
          height="500px"
        ></video>
        <div v-else>加载视频中...</div>
      </div>
      <div class="comments-section">
        <h2>评论区</h2>
        <div v-for="comment in comments" :key="comment.id" class="comment">
          <img :src="comment.avatar || '../../assets/img/2.jpg'" alt="用户头像" class="avatar" />
          <div class="comment-content">
            <span class="nickname">{{ comment.nickname }}</span>
            <p>{{ comment.content }}</p>
            <p>{{ comment.gmtCreate }}</p>
          </div>
        </div>
        <el-input v-model="newComment" style="width: 100%" :rows="4" type="textarea" placeholder="发表评论..." />
        <div class="button-Comment">
          <el-button type="primary" @click="addComment">发布</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { useRoute } from "vue-router";
import axios from "../../assets/js/axios";
import { onMounted, ref } from "vue";
import { jwtDecode } from "jwt-decode";
import { ElMessage } from "element-plus";
import { log } from "console";
import { nextTick } from "vue";
// 在这里定义 getUserIdFromToken 函数
const getUserIdFromToken = () => {
  const token = localStorage.getItem("userToken");
  if (token) {
    try {
      const decoded: any = jwtDecode(token);
      return {
        userId: decoded.id,
        nickname: decoded.nickname,
        avatar: decoded.avatar,
      };
    } catch (error) {
      console.error("Token解析失败", error);
      return null;
    }
  }
  return null;
};

// 定义其他数据状态
const comments = ref<any[]>([]);
const route = useRoute();
const newComment = ref("");
const playURL = ref<string | null>(null);
const videoPlayer = ref<HTMLVideoElement | null>(null);
const userData = getUserIdFromToken();  // 现在可以安全使用

if (!userData) {
  ElMessage.error("用户信息获取失败");
}

const saveWatchPosition = () => {
  const vid = route.query.vid;
  if (videoPlayer.value) {
    const currentTime = videoPlayer.value.currentTime;
    const videoId = String(route.query.videoId);
    const courseId = String(route.query.courseId);
    console.log(courseId);
    
    if (userData && userData.userId) {
      axios
        .post("/serviceedu/edu-watchhistory/save/", {
          userId: userData.userId,
          vid,
          courseId,
          videoId,
          lastPosition: Math.floor(currentTime),
        })
        .then(() => {
          console.log("播放进度已保存");
        })
        .catch((err) => {
          console.error("保存播放进度时出错: ", err);
        });
    }
  }
};
const lastPosition = ref<number | null>(
  route.query.lastPosition ? Number(route.query.lastPosition) : null
);

onMounted(async () => {
  const videoId = route.query.videoId;
  const vid = route.query.vid;
  console.log("初始 lastPosition:", lastPosition.value);

  if (userData && videoId) {
    // 获取播放历史
    console.log("请求参数:", { userId: userData.userId, videoId });
    try {
      const res = await axios.get("/serviceedu/edu-watchhistory/get/", {
        userId: userData.userId,
        videoId,
      });
      console.log("后端响应:", res);
      if (res.code === 200) {
        lastPosition.value = res.data.watchHistory.lastPosition
          ? Number(res.data.watchHistory.lastPosition)
          : null;
        console.log("从后端获取的 lastPosition:", lastPosition.value);
      }

      // 获取视频播放地址
      const authRes = await axios.get(`/serviceedu/edu-video/getPlayAuth/${videoId}`, {});
      console.log("getPlayAuth 返回结果:", authRes);
      if (authRes.code === 200 && authRes.data.playAuth) {
        const playAuth = authRes.data.playAuth;
        const urlResponse = await axios.get(`/serviceedu/edu-video/getPlayURL`, {
          playAuth,
          videoId,
        });
        console.log("getPlayURL 返回结果:", urlResponse);
        if (urlResponse.code === 200) {
          playURL.value = urlResponse.data.playURL;
          console.log("获取到播放地址:", playURL.value);

          // 等待 DOM 更新
          await nextTick();

          // 此时 videoPlayer 应该已经可用
          if (videoPlayer.value) {
            const waitForMetadata = new Promise<void>((resolve) => {
              videoPlayer.value.addEventListener("loadedmetadata", () => {
                console.log("loadedmetadata 触发");
                resolve();
              });
            });

            await waitForMetadata;
            if (lastPosition.value !== null) {
              videoPlayer.value.currentTime = lastPosition.value; // 设置播放位置
              console.log("设置视频播放位置为:", lastPosition.value);
            }
          } else {
            console.error("videoPlayer 仍然为 null");
          }
        } else {
          console.error("无法获取播放地址: ", urlResponse.message);
        }
      }
    } catch (err) {
      console.error("网络错误或请求失败: ", err);
    }
  }
});


const getComment = () => {
  axios.get("/serviceedu/edu-comment/CommentList",{}).then((res: any) => {
    if (res.code === 200) {
      comments.value = res.data.list;
    }
  });
};
getComment();

const addComment = () => {
  if (!newComment.value.trim()) {
    ElMessage.error("评论内容不能为空");
    return;
  }

  if (userData) {
    axios
      .post("/serviceedu/edu-comment/addComment", {
        courseId: route.query.courseId,
        teacherId: route.query.teacherId,
        userId: userData.userId,
        nickname: userData.nickname,
        avatar: userData.avatar,
        content: newComment.value,
      })
      .then((res: any) => {
        if (res.code === 200) {
          ElMessage.success("评论发布成功");
          newComment.value = "";
          getComment();
        }
      });
  }
};
</script>
<style lang="less" scoped>
.comments-section {
  margin: 20px;
}
.comment {
  display: flex;
  margin-top: 10px;
  margin-bottom: 20px;
}
.avatar {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  margin-right: 10px;
}
.comment-content {
  p {
    margin-top: 10px;
  }
  .nickname {
    font-weight: bold;
  }
}
.button-Comment {
  display: flex;
  justify-content: flex-end; /* 右对齐 */
  margin-top: 10px;
}
</style>
